import { resources, swaggerAuth } from '@/services/swagger';
import {message} from 'antd';
import authorize from "@/components/Authorized/Secured";
// import {queryCurrent} from "@/services/user";

// swagger api
const SwaggerModel = {
  namespace: 'swagger',
  state: {
    swaggerData: [],
    selectedSwagger: '',
    authorization: '',
  },
  effects: {
    *resources(_, { call, put }) {
      const response = yield call(resources);
      yield put({
        type: 'setResources',
        payload: response,
      });
    },
    *swaggerAuth(_, { call, put }){
      const params = {
        swaggerAuthUrl: localStorage.getItem('swaggerAuthUrl'),
        swaggerAuthUsername: localStorage.getItem('swaggerAuthUsername'),
        swaggerAuthPassword: localStorage.getItem('swaggerAuthPassword'),
      }
      const response = yield call(swaggerAuth,params);
      yield put({
        type: 'setAuth',
        payload: response,
      });
    }
  },
  reducers: {
    setResources(state, action) {
      return {
        ...state,
        swaggerData: action.payload || {},
        selectedSwagger: action.payload !== undefined && action.payload.length>0 ? action.payload[0].url : '',
      };
    },
    setSelected(state, { swaggerUrl: url }) {
      return {
        ...state,
        selectedSwagger: url,
      };
    },
    setAuth(state, action){
      const {payload} = action;
      if (payload.code !== "000"){
        message.error(payload.msg);
        return
      }
      const token = payload.result.tails.access_token;
      // console.log("更新token -> " + token);
      localStorage.setItem("token", token);
      return {
        ...state,
        authorization: token,
      }
    },
    clearAuth(state){
      // console.log("删除token")
      localStorage.setItem("token", undefined);
      return {
        ...state,
        authorization: undefined,
      }
    },
    updateAuth(state, {authorization: authorization}){
      // console.log("更新token -> " + authorization);
      localStorage.setItem("token", authorization);
      return {
        ...state,
        authorization: authorization,
      }
    }
  }
}

export default SwaggerModel;
